﻿using System.Collections.Generic;
using DataScripter.Containers;
using DataScripter.Scripting.Processes.Output;

namespace DataScripter.Scripting.Processes
{
    public abstract class BaseProcess : IProcess
    {
        public string Name { get; set; }
        public IContainer Container { get; set; }
        public ProcessState State { get; protected set; }
        protected readonly List<IProcess> InputProcesses = new List<IProcess>();
        public IProcessOutput Output { get; protected set; }

        public BaseProcess(string name, IContainer container)
        {
            Name = name;
            Container = container;
            State = ProcessState.NotStarted;
        }

        public abstract IProcessOutput Run();
        public abstract void Initialize(Dictionary<string, string> parameters);

        public void AddDependency(IProcess parentProcess)
        {
            InputProcesses.Add(parentProcess);
        }

        protected T GetTypedParameter<T>(IDictionary<string, string> parameters, string parameterName)
        {
            if (parameters.ContainsKey(parameterName))
            {
                string parameter = parameters[parameterName];
                return Container.Resolve<T>(parameter);
            }
            return Container.Resolve<T>();
        }

        protected void RunParents()
        {
            foreach (IProcess parent in InputProcesses)
            {
                switch (parent.State)
                {
                    case ProcessState.NotStarted:
                        parent.Run();
                        break;
                    case ProcessState.Started:
                        // wait until ended
                        break;
                    case ProcessState.Ended:
                        break;
                    case ProcessState.Error:
                        State = ProcessState.Error;
                        break;
                }
            }
        }
    }
}
